package com.example.museum.controller;


import com.example.museum.common.Result;
import com.example.museum.entity.ShoppingCart;
import com.example.museum.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 购物车
 */

//ToDo 需要修改
@RestController
@RequestMapping("/cart")
@Slf4j
public class ShoppingCartController {

    @Autowired
    private CartService cartService;

    /**
     * 获取购物车列表
     */
    @GetMapping("/list")
    public Result<List<ShoppingCart>> getCartItems(ShoppingCart shoppingCart) {
        log.info("购物车为：{}", shoppingCart);
//        Long userId = BaseContext.getUserId();
        Long userId = shoppingCart.getUserId();
        List<ShoppingCart> ShoppingCarts = cartService.getCartItemsByUserId(userId);
        return Result.success(ShoppingCarts);
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public Result<String> addToCart(@RequestBody ShoppingCart shoppingCart) {
        log.info("添加到购物车为：{}", shoppingCart);
//        Long userId = BaseContext.getUserId();
        cartService.addToCart(shoppingCart);
        return Result.success("添加成功");
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/update/{id}")
    public Result<String> updateCartItem(@PathVariable Long id,Integer quantity) {
        cartService.updateCartItemQuantity(id, quantity);
        return Result.success("更新成功");
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> removeCartItem(@PathVariable Long id) {
        cartService.removeCartItem(id);
        return Result.success("删除成功");
    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/clear/{userId}")
    public Result<String> clearCart(@PathVariable Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        cartService.clearCart(userId);
        return Result.success("清空成功");
    }
}